﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace WRJClient.Common
{
    public class MessageEventArgs : EventArgs
    {
        public string Level;
        public string Message;
    }

    public class MessageData
    {
        public string Level { get; set; }
        public string Message { get; set; }
        public string Detail { get; set; }
        public DateTime Time { get; set; }
    }

    public sealed class MessageManager
    {
        public delegate void ShowMessageHandler(object sender, MessageEventArgs e);
        public event ShowMessageHandler ShowMessage = null;

        private ObservableCollection<MessageData> _msgs = new ObservableCollection<MessageData>();
        public ObservableCollection<MessageData> Msgs { get { return _msgs; } }

        private static readonly MessageManager _instance = new MessageManager();
        public static MessageManager Instance { get { return _instance; } }
        private MessageManager() { }

        private void addMessage(string level, string msg, string detail)
        {
            Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate ()
           {
               MessageData data = new MessageData { Level = level, Message = msg, Time = DateTime.Now, Detail = detail };
               _msgs.Add(data);

               MessageEventArgs e = new MessageEventArgs { Message = msg, Level = level };
               ShowMessage?.Invoke(this, e);
           });
        }


        public void Success(string msg, string detail = null)
        {
            addMessage("success", msg, detail);
        }
        public void Info(string msg, string detail = null)
        {
            addMessage("info", msg, detail);
        }
        public void Warning(string msg, string detail = null)
        {
            addMessage("warning", msg, detail);
        }
        public void Error(string msg, string detail = null)
        {
            addMessage("error", msg, detail);
        }
    }
}
